package com.example.mssql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity implements OnClickListener{

	Button bSorgula;
	EditText etID, etKategoriAdi, etAciklama;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		bSorgula = (Button) findViewById(R.id.bSorgula);
		bSorgula.setOnClickListener(this);

		etID = (EditText) findViewById(R.id.etID);
		etKategoriAdi = (EditText) findViewById(R.id.etKategoriAdi);
		etAciklama = (EditText) findViewById(R.id.etAciklama);

	}

	@Override
	public void onClick(View v) {

		try {
			try {
				Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
			} catch (InstantiationException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		new Thread(new Runnable() {

			public void run() {

				runOnUiThread(new Runnable() {
					public void run() {
						ResultSet results = null;

						try {
							Connection conn = DriverManager
									.getConnection(
											"jdbc:jtds:sqlserver://213.142.139.96:1433;databaseName=Northwind",
											"sa", "ser8540duru");

							Statement statement = conn.createStatement();
							statement = conn.createStatement(
									ResultSet.TYPE_SCROLL_INSENSITIVE,
									ResultSet.CONCUR_READ_ONLY);

							int ID = Integer.valueOf(etID.getText().toString());

							String sorgu = "SELECT CategoryID,CategoryName,Description FROM Categories WHERE CategoryID ="
									+ ID;

							results = statement.executeQuery(sorgu);

							results.last();
							int kayitSayisi = 0;
							if (results != null) {
								kayitSayisi = results.getRow();
							}
							results.beforeFirst();

							if (results != null && kayitSayisi != 0) {
								while (results.next()) {

									String kategoriAdi = results
											.getString("CategoryName");

									String aciklama = results
											.getString("Description");

									etKategoriAdi.setText(kategoriAdi);
									etAciklama.setText(aciklama);
								}

							} else {

							}

						} catch (SQLException e) {
							e.printStackTrace();
						}
					}
				});

			}
		}).start();

	}
}
